package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import net.sf.json.JSONObject;
import server.query.AutoRecorder;
import server.query.QueryHandler;

public class DynamicHandler implements HttpHandler {

    public static final Map <String, QueryHandler> handlers = new HashMap<>();

    public static void init () {
        handlers.put("save", AutoRecorder.saveRecord);
    }

    public static Map<String, String> getCookie (HttpExchange e) {
        Map<String, String> map = new HashMap<>();
        List<String> cookie = e.getRequestHeaders().get("Cookie");
        if (cookie == null || cookie.size() == 0) {
            return null;
        }
        for (String c : cookie.get(0).split(";")) {
            String[] kv = c.split("=");
            map.put(kv[0], kv[1]);
        }
        return map;
    }

    public static JSONObject URLToJson (String url) {
        url = "{\"" + url + "\"}";
        url = url.replaceAll("=", "\":\"");
        url = url.replaceAll("&", "\",\"");
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        JSONObject object = JSONObject.fromObject(url);
        return object;
    }
    
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        try {
            InputStream in = httpExchange.getRequestBody();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String text = "";
            String line;
            while ((line = reader.readLine()) != null) {
                text += line;
            }
            //JSONObject object = URLToJson(text);
            JSONObject object = JSONObject.fromObject(text);
            if (object == null) {
                throw new Exception("Json = null");
            }
            //System.out.println(object);
            String request = object.getString("request");
            if (handlers.containsKey(request)) {
                String response = handlers.get(request).handle(httpExchange, object);
                if (response != null) {
                    byte[] r = response.getBytes("UTF-8");
                    httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, r.length);
                    OutputStream out = httpExchange.getResponseBody();
                    out.write(r);
                    out.flush();
                    out.close();
                } else {
                    httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0);
                }
            } else {
                httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_METHOD, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                JSONObject response = new JSONObject();
                response.put("success", false);
                response.put("message", e.getMessage());
                httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
                byte[] r = response.toString().getBytes("UTF-8");
                httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, r.length);
                OutputStream out = httpExchange.getResponseBody();
                out.write(r);
                out.flush();
                out.close();
            } catch (Exception e1) {
            }
        } finally {
            httpExchange.close();
        }
    }
}